/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */

package filesecurity;

import java.io.File;
import java.security.KeyFactory;
import java.security.NoSuchAlgorithmException;
import java.security.PrivateKey;
import java.security.spec.InvalidKeySpecException;
import java.security.spec.PKCS8EncodedKeySpec;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.crypto.SecretKey;
import javax.swing.JFileChooser;
import javax.swing.JOptionPane;

/**
 *
 * @author lehoangkhanh
 */
public class DecryptForm extends javax.swing.JInternalFrame {

    /**
     * Creates new form PassPhraseRequire
     */
    String fileName = null;
    String filePath = null;
    MainFrame rootFrame = null; 
    public DecryptForm(MainFrame root) {
        initComponents();
        rootFrame = root;
    }

    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jLabel1 = new javax.swing.JLabel();
        passphrase = new javax.swing.JTextField();
        jToggleButton1 = new javax.swing.JToggleButton();
        jLabel3 = new javax.swing.JLabel();
        savein = new javax.swing.JToggleButton();

        setClosable(true);
        setIconifiable(true);
        setTitle("Decrypt");

        jLabel1.setText("PassPhrase:");

        jToggleButton1.setText("OK <<");
        jToggleButton1.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jToggleButton1ActionPerformed(evt);
            }
        });

        jLabel3.setText("Save in:");

        savein.setText("...");
        savein.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                saveinMouseClicked(evt);
            }
        });
        savein.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                saveinActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addGap(40, 40, 40)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jLabel1)
                    .addComponent(jLabel3))
                .addGap(18, 18, 18)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jToggleButton1)
                    .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                        .addComponent(passphrase)
                        .addComponent(savein, javax.swing.GroupLayout.PREFERRED_SIZE, 129, javax.swing.GroupLayout.PREFERRED_SIZE)))
                .addContainerGap(57, Short.MAX_VALUE))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                .addContainerGap(32, Short.MAX_VALUE)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel1)
                    .addComponent(passphrase, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel3)
                    .addComponent(savein))
                .addGap(21, 21, 21)
                .addComponent(jToggleButton1, javax.swing.GroupLayout.PREFERRED_SIZE, 32, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addContainerGap())
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void saveinActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_saveinActionPerformed
        // TODO add your handling code here:
    }//GEN-LAST:event_saveinActionPerformed

    private void jToggleButton1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jToggleButton1ActionPerformed
        // TODO add your handling code here:
        if(passphrase.getText().equals("")){
            JOptionPane.showMessageDialog(rootPane, "PassPhrase is NULL!!!");
            return;
        }
        if(fileName==null || fileName.equals("")){
            JOptionPane.showMessageDialog(rootPane, "Please select location of output file!!!");
            return;
        }
        User currentUser = rootFrame.getCurrentUser();
        boolean validState = Crypto.checkHash(passphrase.getText().getBytes(), currentUser.getHashPassPhrase(), currentUser.getSaltPassPhrase());
        if(validState == false){
            JOptionPane.showMessageDialog(rootPane, "PassPhrase is not valid!!!");
            return;
        }
        //read file
        byte[] file = Utils.readFile(rootFrame.getFilePath());
        //get header & algo
        byte[] header = Utils.getHeader(file);
        int algo = Utils.getAlgo(header);
        //decrypt primary key
        byte[] encryptedPriKey = currentUser.getEncryptedPrivateKey();
        byte[] priKeyByte =  Crypto.decryptFile(encryptedPriKey, KeyFac.sKeyGenWithPass(passphrase.getText()), Crypto.AES, "itisnotcareabout".getBytes());
        if(priKeyByte == null){
            JOptionPane.showMessageDialog(rootPane, "Error!!!Please try again");
            return;
        }
        PrivateKey priKey = null;
        try {
            priKey = KeyFactory.getInstance("RSA").generatePrivate(new PKCS8EncodedKeySpec(priKeyByte));
        } catch (NoSuchAlgorithmException ex) {
            Logger.getLogger(DecryptForm.class.getName()).log(Level.SEVERE, null, ex);
        } catch (InvalidKeySpecException ex) {
            Logger.getLogger(DecryptForm.class.getName()).log(Level.SEVERE, null, ex);
        }
        //decrypt secret key
        byte[] encryptedKey = Utils.getEncryptedKey(header);
        SecretKey key = Crypto.decryptKey(encryptedKey, priKey, algo);
        if(key == null){
            JOptionPane.showMessageDialog(rootPane, "Error!!!Please try again");
            return;
        }
        //get iv
        byte[] iv = Utils.getIV(header);
        //get encrypted data & remove header
        byte[] encryptedData = Utils.removeHeader(file);
        //decrypt file
        byte[] data = Crypto.decryptFile(encryptedData, key, algo, iv);
        if(data!= null){
            Utils.writeFile(data, filePath+"/"+fileName);
            JOptionPane.showMessageDialog(rootPane, "Decrypt file successful!!!");
            this.setVisible(false);
            return;
        }
        JOptionPane.showMessageDialog(rootPane, "Error!!!Please try again");
    }//GEN-LAST:event_jToggleButton1ActionPerformed

    private void saveinMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_saveinMouseClicked
        // TODO add your handling code here:
        JFileChooser file = new JFileChooser();
        file.setSelectedFile(new File(rootFrame.getFileName().replace(".encrypted", "")));
        int op = file.showSaveDialog(null);
        if(op == JFileChooser.APPROVE_OPTION){
            filePath = file.getCurrentDirectory().getPath().toString();
            fileName = file.getSelectedFile().getName();
            savein.setText("Just Selected...");
            savein.setToolTipText(filePath);
        }
    }//GEN-LAST:event_saveinMouseClicked


    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel3;
    private javax.swing.JToggleButton jToggleButton1;
    private javax.swing.JTextField passphrase;
    private javax.swing.JToggleButton savein;
    // End of variables declaration//GEN-END:variables
}
